package cn.hinglo.permission.service;

import cn.hutool.core.collection.CollUtil;
import cn.hinglo.common.util.SysCommonKit;
import cn.hinglo.permission.model.Code;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.SqlPara;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author HingLo
 * @createTime: 2020-05-18 16:48:12
 * @description: CodeService 服务层
 */
@Slf4j
public class CodeService {

    /**
     * Code列表
     *
     * @param page 页码
     * @param size 大小
     * @return Code分页后集合
     */
    public Map<String, Object> listCodeService(Integer page, Integer size, String codeKey) {
        Record record = new Record();
        record.set("codeKey", codeKey);
        SqlPara sql = Db.getSqlPara("code.list", record);
        Page<Record> list = Db.paginate(page, size, sql);
        return SysCommonKit.pageKit(list.getTotalRow(), list.getList());
    }

    /**
     * 添加Code
     *
     * @param code Code对象信息
     * @return 操作结果
     */
    public boolean addCodeService(Code code) {
        return code.save();
    }

    /**
     * 删除Code对象
     *
     * @param id Code对象的唯一ID
     * @return 操作结果
     */
    public boolean deleteCodeService(Integer id) {
        return id != null && Code.dao.deleteById(id);
    }

    /***
     * 通过Key 获取value
     * @param key key
     * @return 返回结果
     */
    public String getCodeValue(String key) {
        String sql = Db.getSql("code.codeValue");
        List<Code> records = Code.dao.find(sql, key);
        List<String> result = new ArrayList<>();
        for (Code record : records) {
            result.add(record.getCodeValue());
        }
        return CollUtil.join(result, ",");
    }

    /***
     * 字典更新信息
     * @param code code
     * @return 返回更新信息
     */
    public boolean updateService(Code code) {
        return code.update();
    }
}

